dojo.provide('jetty.httpservlet');
dojo.provide('jetty.httpservlet.RequestHandler');

dojo.require('jetty.Request');
dojo.require('jetty.Response');
ph.require('javax.servlet.http.HttpServletResponse');
ph.require('org.mortbay.jetty.servlet.ServletHolder');
ph.require('com.google.code.physicaljs.jetty.HttpServlet');

dojo.declare('jetty.httpservlet.RequestHandler', null, {
  constructor: function(callbacks) {
    this._callbacks = callbacks;
  },
  
  handleRequest: function(req, resp) {
    var request  = new jetty.Request(req);
    var response = new jetty.Response(resp);
    
    var method = request.method.toLowerCase();
    if (method in this._callbacks) {
      this._callbacks[method](request, response);
    } else {
      if (/1\.1$/.test(request.http)) response.error(javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED);
      else response.error(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
    }
    
    jetty.Response.commit(response, resp);
  }
});


jetty.httpservlet.createDescriptor = function(callbacks) {
  var handler    = new jetty.httpservlet.RequestHandler(callbacks);
  var descriptor = {};
  
  descriptor.adapter     = new JavaAdapter(com.google.code.physicaljs.jetty.HttpServlet, handler);
  descriptor.name        = descriptor.adapter.getClass().getName();
  descriptor.classloader = descriptor.adapter.getClass().getClassLoader();
  descriptor.holder      = new JavaAdapter(org.mortbay.jetty.servlet.ServletHolder, {
    newInstance: function() {
      return new JavaAdapter(com.google.code.physicaljs.jetty.HttpServlet, handler);
    }
  });
  descriptor.holder.setName(descriptor.name);
  descriptor.holder.setClassName(descriptor.name);
  
  return descriptor;
};
